package eva

import (
	"context"
	"trusteva/app/eva/internal/ruleutil"
	"trusteva/app/eva/model"

	"trusteva/app/eva/internal/svc"
	"trusteva/app/eva/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddRuleLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAddRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddRuleLogic {
	return &AddRuleLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AddRuleLogic) AddRule(req *types.AddRuleRo) (resp *types.AddRuleRsp, err error) {
	rule := model.Rule{
		AppId:    req.AppId,
		DeviceId: req.DeviceId,
		DstIP:    req.DstIP,
		DstPort:  req.DstPort,
		Status:   req.Status,
		UserId:   req.UserId,
	}
	rules, err := ruleutil.ParseRules(rule)
	if err != nil {
		return nil, err
	}

	for _, v := range rules {
		r := model.Rule{
			AppId:    v.AppId,
			DeviceId: v.DeviceId,
			DstIP:    v.DstIP,
			DstPort:  v.DstPort,
			Status:   v.Status,
			UserId:   v.UserId,
		}
		err = l.svcCtx.DB.WithContext(l.ctx).Create(&r).Error
		if err != nil {
			return nil, err
		}
	}

	if rule.Status == model.RulePass {
		for _, v := range rules {
			_, err = l.svcCtx.RedisClient.SaddCtx(l.ctx, model.RuleSetKey, v.Key())
			if err != nil {
				logx.Error("SaddCtx", v.Key(), err)
				return nil, err
			}
		}
	}

	return
}
